package com.aixin.project.handler;

import com.aixin.project.conf.Configure;
import com.aixin.project.data.*;
import com.aixin.project.db.CourseDao;
import com.aixin.project.util.AxMemcached;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: Sufeng
 * Date: 12-4-22
 * Time: 上午1:27
 * To change this template use File | Settings | File Templates.
 */
public class CourseHandler {
    private static int ORDERNUM = 4;
    private static final int UNPAYORDERNUM = 2;
    private static final int EXPERT_COURSENUM = 4;
    private static final int EXPERT_WARN_COURSENUM = 2;
    private static final int PAGE_NUM=8;

    public static Course find(long cid) {
        Course course = (Course) AxMemcached.get(CommonConstants.MKEY_COURSE + cid);
        if (course == null) {
            course = CourseDao.find(cid);
            if (course != null)
                AxMemcached.set(CommonConstants.MKEY_COURSE + cid, course, new Date(CommonConstants.MEMCACHED_SESSION_TIMEOUT_WEEK * 1000));
        }
        return course;
    }
    
    public static Course findByCid(long cid) {
       return CourseDao.find(cid);
    }


    public static HashMap<String, List<Course>> orderList(long uid) {
        HashMap<String, List<Course>> ordersMap = null;
        ArrayList<Course> unpayOrderList = new ArrayList<Course>();
        ArrayList<Course> payOrderList = new ArrayList<Course>();
        List<CourseOrder> orderList = (List<CourseOrder>) AxMemcached.get(CommonConstants.MKEY_COURSEORDER_LIST + uid);
        if (orderList == null) {
            orderList = CourseDao.listByUser(uid);
            AxMemcached.set(CommonConstants.MKEY_COURSEORDER_LIST + uid, orderList, new Date(CommonConstants.MEMCACHED_SESSION_TIMEOUT_WEEK * 1000));
        }

        if (orderList != null && orderList.size() > 0) {
            ordersMap = new HashMap<String, List<Course>>();
            for (CourseOrder order : orderList) {
                Course c = find(order.getCourseid());
                Expert ex = ExpertHandler.find(order.getExportid());

                if (c != null) {
                    c.setPoint(order.getPoint());
                    c.setTotalprice(order.getPrice());
                    c.setExpertname(ex.getName());
                    c.setCoid(order.getId());
                }
                if (order.getStatus() == 0 && !c.getStatus().equals("已结束")) { //预定
                    if (unpayOrderList.size() < UNPAYORDERNUM)
                        unpayOrderList.add(c);
                } else if (order.getStatus() == 1 && !(c.getStatus()).equals("已结束")) {

                    if (payOrderList.size() < ORDERNUM)
                        payOrderList.add(c);
                }
            }
            ordersMap.put(CourseStatus.PAYORDER.toString(), payOrderList);
            ordersMap.put(CourseStatus.UNPAYORDER.toString(), unpayOrderList);
        }
        return ordersMap;
    }


    public static HashMap<String, List<Course>> courseList(long eid) {
        Date now = new Date();
        long nowtimeL = now.getTime();
        long hour = 60 * 60 * 1000;
        HashMap<String, List<Course>> courseMap = new HashMap<String, List<Course>>();
        ArrayList<Course> list = new ArrayList<Course>();
        ArrayList<Course> liveList = new ArrayList<Course>();
        List<Integer> courseIdList = (List<Integer>) AxMemcached.get(CommonConstants.MKEY_E_ALL_COURSE_LIST + eid);
        if (courseIdList == null || courseIdList.size()==0) {
            courseIdList = CourseDao.listCourseIdByExpert(eid);
            if(courseIdList!=null && courseIdList.size()>0)
                AxMemcached.set(CommonConstants.MKEY_E_ALL_COURSE_LIST + eid, courseIdList, new Date(CommonConstants.MEMCACHED_SESSION_TIMEOUT_WEEK * 1000));
        }

        if (courseIdList != null && courseIdList.size() > 0) {
            for (Integer cid : courseIdList) {
                Course c = find(cid);
                if(c == null) continue;
                long pretimeL = c.getStarttime().getTime() - hour * Configure.EXPERTCOURSE_TIME;
                long starttimeL = c.getStarttime().getTime();
                System.out.println("nowtime : " + nowtimeL);
                System.out.println("pretimeL : " + pretimeL);
                System.out.println("starttimeL : " + starttimeL);
                if (c.getStatus().equals("未开始")) {
                    if (list.size() < EXPERT_COURSENUM) ;
                    list.add(c);
                }
                if (nowtimeL >= pretimeL && nowtimeL < starttimeL) {
                    getCourseOrderInfo(c);
                    if (liveList.size() < EXPERT_WARN_COURSENUM)
                        liveList.add(c);
                }
            }
            courseMap.put(CourseStatus.WARNCOURSE.toString(), liveList);
            courseMap.put(CourseStatus.NOSTARTCOURSE.toString(), list);
        }
        return courseMap;
    }

    private static Course getCourseOrderInfo(Course c) {
        Object point = (String) AxMemcached.get(CommonConstants.MKEY_POINT + c.getId());
        if (point == null) {
            Object p = CourseDao.findPoint(c.getId());
            if (p != null) {
                c.setPoint(Integer.parseInt(p.toString()));
                AxMemcached.set(CommonConstants.MKEY_POINT + c.getId(), point, new Date(CommonConstants.MEMCACHED_SESSION_TIMEOUT_WEEK * 1000));
            }
        }
        Object usernum = AxMemcached.get(CommonConstants.MKEY_USERNUM + c.getId());
        if (usernum == null) {
            Object unum = CourseDao.findUsersByCid(c.getId());
            if (unum != null) {
                c.setUsernum(Integer.parseInt(unum.toString()));
                AxMemcached.set(CommonConstants.MKEY_USERNUM + c.getId(), unum, new Date(CommonConstants.MEMCACHED_SESSION_TIMEOUT_WEEK * 1000));
            }
        }

        return c;
    }


    //状态 1已结束 2,未开始 3
    public static HashMap<String, Integer> courseStatusByEid(long eid) {
        System.out.println("courseStatusByEid:" + 1);
        int liveCount = 0;
        int finishCount = 0;
        int nostartCount = 0;
        HashMap<String, Integer> courStatusMap = new HashMap<String, Integer>();
        List<Integer> courseIdList = (List<Integer>) AxMemcached.get(CommonConstants.MKEY_E_ALL_COURSE_LIST + eid);
        if (courseIdList == null || courseIdList.size()==0) {
            courseIdList = CourseDao.listCourseIdByExpert(eid);
            if(courseIdList!=null && courseIdList.size()>0)
                AxMemcached.set(CommonConstants.MKEY_E_ALL_COURSE_LIST + eid, courseIdList, new Date(CommonConstants.MEMCACHED_SESSION_TIMEOUT_WEEK * 1000));
        }
        if (courseIdList != null && courseIdList.size() > 0) {
            for (Integer cid : courseIdList) {
                Course c = find(cid);
                if(c == null) continue;
                if (c.getStatus().equals("已结束"))
                    finishCount++;
                if (c.getStatus().equals("未开始") /*|| c.getStatus().equals("进行中")*/)
                    nostartCount++;
                if (c.getStatus().equals("进行中"))
                    liveCount++;
            }
            courStatusMap.put(CourseStatus.LIVE.toString(), liveCount);
            courStatusMap.put(CourseStatus.FINISH.toString(), finishCount);
            courStatusMap.put(CourseStatus.NOSTART.toString(), nostartCount);
        }


        return courStatusMap;
    }


    public static Map<String,Integer> courseStatusCount(long uid){
    	Map<String, Integer> courseStatusMap = new HashMap<String, Integer>();
        List<CourseOrder> orderList = (List<CourseOrder>) AxMemcached.get(CommonConstants.MKEY_COURSEORDER_LIST + uid);
        if (orderList == null) {
            orderList = CourseDao.listByUser(uid);
            AxMemcached.set(CommonConstants.MKEY_COURSEORDER_LIST + uid, orderList, new Date(CommonConstants.MEMCACHED_SESSION_TIMEOUT_WEEK * 1000));
        }
        int wzf=0,zbz=0,wks=0;
        if (orderList != null && orderList.size() > 0) {
        	for (CourseOrder order : orderList) {
                Course c = CourseDao.find(order.getCourseid());
                if("未开始".equals(c.getStatus())){
                	wks++;
                }else if("进行中".equals(c.getStatus())){
                	zbz++;
                }
                if(!"1".equals(order.getStatus())){
                	wzf++;
                }
            }
        }
        courseStatusMap.put("wks", wks);
        courseStatusMap.put("zbz", zbz);
        courseStatusMap.put("wzf", wzf);
        return courseStatusMap;
    }
    
    
    //状态 1已结束 2,未开始
    public static HashMap<String, Integer> courseStatusByUid(long id) {
        int finishCount = 0;
        int nostartCount = 0;

        HashMap<String, Integer> courseStatusMap = null;
        List<CourseOrder> orderList = (List<CourseOrder>) AxMemcached.get(CommonConstants.MKEY_COURSEORDER_LIST + id);
        if (orderList == null) {
            orderList = CourseDao.listByUser(id);
            AxMemcached.set(CommonConstants.MKEY_COURSEORDER_LIST + id, orderList, new Date(CommonConstants.MEMCACHED_SESSION_TIMEOUT_WEEK * 1000));
        }

        if (orderList != null && orderList.size() > 0) {
            courseStatusMap = new HashMap<String, Integer>();
            for (CourseOrder order : orderList) {
                Course c = CourseDao.find(order.getCourseid());
                if (c.getStatus().equals("已结束"))
                    finishCount++;
                if (c.getStatus().equals("未开始") || c.getStatus().equals("进行中"))
                    nostartCount++;
            }
            courseStatusMap.put(CourseStatus.FINISH.toString(), finishCount);
            courseStatusMap.put(CourseStatus.NOSTART.toString(), nostartCount);
        }
        return courseStatusMap;
    }

    public static List<Course> listComingCourse() {
        List<Course> courses = null;
        List<Integer> courseids = null;
        Object obj = AxMemcached.get(CommonConstants.MKEY_COMING_COURSELIST);
        if (null == obj) {
            courseids = CourseDao.listComingCourseId();
            if (null != courseids && courseids.size()>0) {
                AxMemcached.set(CommonConstants.MKEY_COMING_COURSELIST, courseids, new Date(CommonConstants.MEMCACHED_SESSION_TIMEOUT_HOUR * 1000));
            }
        } else{
            courseids = (List<Integer>) obj;
        }

        if (null != courseids && courseids.size() > 0) {
            courses = new ArrayList<Course>();
            for (Integer cid : courseids) {
                Course c = find(cid);
                if (c == null) continue;
                Expert e = ExpertHandler.find(c.getExpertid());
                if (e != null) {
                    c.setExpertname(e.getName());
                    c.setExpertdes(e.getDescription());
                }
                courses.add(c);
            }
        }
        return courses;
    }
    
    
    public static List<Course> listCourse(){
    	List<Course> courseList=listComingCourse();
    	List<Course> cslist=new ArrayList<Course>();
    	if(courseList!=null && courseList.size()>0){
    		for(Course c :courseList){
    			Expert ex=ExpertHandler.find(c.getExpertid());
    			if(ex!=null){
    				c.setExpertname(ex.getName());
    				cslist.add(c);
    			}
    		}
    	}
    	return cslist;
    }
    	
    public static int maxpage(int stats){
    	  int maxpage=1;
		  int totalResult=0;
		  Object total=CourseDao.totalRs(stats);

		  if(total!=null){
			  totalResult=Integer.parseInt(total.toString());
			  maxpage=totalResult/PAGE_NUM;
			  maxpage=totalResult%PAGE_NUM==0?maxpage:maxpage+1;  
		  }
		
		  return maxpage;
    
    }
    
    public static List<Course> listByPaggin(int page,int stats){
        List<Course> ret = new ArrayList<Course>() ;  
        List<Course> cslist=new ArrayList<Course>();
       
            ret = CourseDao.listBypagein(PAGE_NUM, page,stats);
            if(ret !=null && ret.size()>0)
            	for(Course c :ret){
        			Expert ex=ExpertHandler.findByUid(c.getExpertid());
        			if(ex!=null){
        				c.setExpertname(ex.getName());
        				cslist.add(c);
        			}
            }
             
        
        return cslist;
    }


    public static int create(Course c) {
        return CourseDao.create(c);
    }
    
    public static int update(Course c){
    	return CourseDao.update(c);
    }
    
    public static int delete(long cid){
    	return CourseDao.delete(cid);
    }

    public static void main(String[] args) {
        System.out.println(CourseStatus.FINISH.toString());
    }

}
